/*
 * @Author: LVGRAPE
 * @LastEditors: LVGRAPE
 */
#ifndef __DRV_SPI_H_
#define __DRV_SPI_H_

#include "drv_pin.h"

#ifdef __cplusplus
extern "C"
{
#endif

/**
 * At CPOL=0 the base value of the clock is zero
 *  - For CPHA=0, data are captured on the clock's rising edge (low->high transition)
 *    and data are propagated on a falling edge (high->low clock transition).
 *  - For CPHA=1, data are captured on the clock's falling edge and data are
 *    propagated on a rising edge.
 * At CPOL=1 the base value of the clock is one (inversion of CPOL=0)
 *  - For CPHA=0, data are captured on clock's falling edge and data are propagated
 *    on a rising edge.
 *  - For CPHA=1, data are captured on clock's rising edge and data are propagated
 *    on a falling edge.
 */
#define RT_SPI_CPHA (1 << 0) /* bit[0]:CPHA, clock phase */
#define RT_SPI_CPOL (1 << 1) /* bit[1]:CPOL, clock polarity */

#define RT_SPI_LSB (0 << 2) /* bit[2]: 0-LSB */
#define RT_SPI_MSB (1 << 2) /* bit[2]: 1-MSB */

#define RT_SPI_MASTER (0 << 3) /* SPI master device */
#define RT_SPI_SLAVE (1 << 3)  /* SPI slave device */

#define RT_SPI_CS_HIGH (1 << 4) /* Chipselect active high */
#define RT_SPI_NO_CS (1 << 5)   /* No chipselect */
#define RT_SPI_3WIRE (1 << 6)   /* SI/SO pin shared */
#define RT_SPI_READY (1 << 7)   /* Slave pulls low to pause */

#define RT_SPI_MODE_MASK (RT_SPI_CPHA | RT_SPI_CPOL | RT_SPI_MSB | RT_SPI_SLAVE | RT_SPI_CS_HIGH | RT_SPI_NO_CS | RT_SPI_3WIRE | RT_SPI_READY)

#define RT_SPI_MODE_0 (0 | 0)                     /* CPOL = 0, CPHA = 0 */
#define RT_SPI_MODE_1 (0 | RT_SPI_CPHA)           /* CPOL = 0, CPHA = 1 */
#define RT_SPI_MODE_2 (RT_SPI_CPOL | 0)           /* CPOL = 1, CPHA = 0 */
#define RT_SPI_MODE_3 (RT_SPI_CPOL | RT_SPI_CPHA) /* CPOL = 1, CPHA = 1 */

#define RT_SPI_BUS_MODE_SPI (1 << 0)
#define RT_SPI_BUS_MODE_QSPI (1 << 1)

    // /**PMW_CSN PB.7 */
    // /**NRF_CSN PC.10 */
    // /**SPL_CSN PA.14 */
    // /**ICM_CSN PA.13 */
    #define PMW_CSN_PIN PB7
    #define NRF_CSN_PIN PC10
    #define SPL_CSN_PIN PA14
    #define ICM_CSN_PIN PA13

    typedef struct spi_dev
    {
        spi_type *instance;
        pin_index_t cs_pin;
        uint8_t mode;
        uint8_t data_width;
        rt_uint32_t max_hz;
    } spi_dev_t;
    void spi1_gpio_config(void);
    void spi2_gpio_config(void);
    void spi2_dma_config(void);
    void spi_dev_init(spi_dev_t *spi);
    int spi_send_then_send(spi_dev_t *spi, uint8_t *txbuf1, uint16_t txlen1, uint8_t *txbuf2, uint16_t txlen2);
    int spi_send_then_receive(spi_dev_t *spi, uint8_t *txbuf, uint16_t txlen, uint8_t *rxbuf, uint16_t rxlen);
#ifdef __cplusplus
}
#endif

#endif /* __DRV_SPI_H_ */
